package com.example.myapplication.util;

import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.media.AudioFormat;
import android.media.AudioRecord;
import android.media.MediaRecorder;

import androidx.core.app.ActivityCompat;

public class SoundSamplingUtil {

    public void sampling(Context context) {
        int sampleRate = 44100; // 采样率
        int channelConfig = AudioFormat.CHANNEL_IN_MONO; // 单声道
        int audioFormat = AudioFormat.ENCODING_PCM_16BIT; // 音频格式
        int bufferSize = AudioRecord.getMinBufferSize(sampleRate, channelConfig, audioFormat);
        if (ActivityCompat.checkSelfPermission(context, Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.

            return;
        }

        AudioRecord audioRecord = new AudioRecord(MediaRecorder.AudioSource.MIC, sampleRate, channelConfig, audioFormat, bufferSize);
        audioRecord.startRecording();
        byte[] audioData = new byte[bufferSize];
        int readSize;
        while ((readSize = audioRecord.read(audioData, 0, bufferSize)) != AudioRecord.ERROR_INVALID_OPERATION) {
            // 处理音频数据
        }
        audioRecord.stop();
        audioRecord.release();


    }
}
